<?php
class CF_Auth_Adapter_Db extends CF_Auth_Adapter_Abstract
{
	/**
	 * 
	 * @var CF_Db_Select
	 */
	protected $_dbSelect;
	
	/**
	 * 
	 * @param CF_Db_Select $dbSelect [optional]
	 */
	public function __construct(CF_Db_Select $dbSelect = null)
	{
		$this->addEvents(
			'beforeauthenticate',
			'authenticate'
		);
		
		if(null !== $dbSelect) $this->setDbSelect($dbSelect);
	}
	
	/**
	 * @return CF_Db_Select
	 */
	public function getDbSelect()
	{
		if(null === $this->_dbSelect){
			$this->_dbSelect = new CF_Db_Select();
		}
		return $this->_dbSelect;
	}
	
	/**
	 * 
	 * @param CF_Db_Select $dbSelect
	 * @return CF_Auth_Adapter_Db $this
	 */
	public function setDbSelect(CF_Db_Select $dbSelect)
	{
		$this->_dbSelect = $dbSelect;
		return $this;
	}
	
	/**
	 * @return object|boolean
	 */
	public function authenticate(CF_Db_Select $dbSelect = null)
	{
		if(null !== $dbSelect) $this->setDbSelect($dbSelect);
		
		# notify before authenticate event
		if(CF_Observable::VALUE_RETURN === $this->fireEvent('beforeauthenticate', array($this, $dbSelect))) return;
		$store = $this->getDbSelect()->execute();
		$res = ($store->getCount() >= 1)? $store->current(true) : false;
		
		# notify authenticate event
		$this->fireEvent('authenticate', array($this, $res));
		
		return $res;
	}
}